package com.ghyf.mplay.receiver;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import com.ghyf.mplay.MPlayActivity;
import com.ghyf.mplay.application.UserInfoSingleton;
import com.ghyf.mplay.net.log.LogTool;
import com.ghyf.mplay.util.LogUtil;
import com.ghyf.mplay.util.VeDate;
import com.ghyf.mplay.value.ConstantValue;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;


/**
 * 系统重启的广播接收者 当系统重启后，程序会接收重启的广播，然后启动app
 * @author 陈小红
 *
 */
public class BootCompleteReceiver extends BroadcastReceiver {
	private static final String TAG="BootCompleteReceiver";
	
	private SharedPreferences sp;
	private Context mContext;
	int count;
	private String filepath=ConstantValue.ROOT_SDCARD_DIR+"1.txt";
	@Override
	public void onReceive(Context context, Intent intent) {
		LogTool.addRunlog("登录注销","设备重启");
		LogUtil.i(TAG, "程序主activity开启");
		mContext=context;
		try {
			 Thread.sleep(500); //延迟开启app等待存储设备挂载成功。
			 writeReboot();
			 
		 } catch (InterruptedException e) {
			 e.printStackTrace();
		 }
		 UserInfoSingleton.setIsreboot("1");
		 
		
		Intent intent2 = new Intent(context, MPlayActivity.class);
		intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent2);
		
	}
	
	public void writeReboot(){
		try{
			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
			count = sp.getInt("countInt", 0);
			count ++;
			Log.i(TAG, "count = " + count);
			File file=new File(filepath);
			if(!file.exists()){
				file.createNewFile();
			}
			//下面把数据写入创建的文件，首先新建文件名为参数创建FileWriter对象
			   FileWriter resultFile = new FileWriter(file,true);
			   //把该对象包装进PrinterWriter对象
			   PrintWriter myNewFile = new PrintWriter(resultFile);
			   //再通过PrinterWriter对象的println()方法把字符串数据写入新建文件
			   boolean isExit=UserInfoSingleton.getBoolean("isExit", false);
			   myNewFile.println(count+",isExit="+isExit+"---- date="+VeDate.getStringDate()+"\n");
			   resultFile.close();   //关闭文件写入流
			   
			Editor editor = sp.edit();
			editor.putInt("countInt", count);
			editor.commit();
//			Toast.makeText(mContext,"第"+ count +"次开机", Toast.LENGTH_SHORT).show();
			UserInfoSingleton.putBooleanAndCommit("isExit", false);
			
		}catch(Exception e){
			 e.printStackTrace();
		}
	
	}
}